#!/bin/bash
########################################
# vim script for automatic backup by neo
########################################

backup_dir=~/.backup
datetime=`date +"%Y-%m-%d.%H:%M:%S"`
current_date=`date +"%Y-%m-%d"`
current_time=`date +"%H:%M:%S"`
filename=`basename $1`
original=$1

if [ ! -d ${backup_dir} ]; then
    mkdir ${backup_dir}
fi

if [ ! -f ${original}.original ]; then
    echo "[${datetime}] [B] ${original} to ${original}.original" >> $backup_dir/history.log
    cp ${original} ${original}.original
fi

if [ -d $backup_dir/${current_date} ]
then
    echo "[${datetime}] [O] ${original}" >> $backup_dir/history.log
else
    mkdir -p $backup_dir/${current_date}
    echo [${datetime}] [C] mkdir $backup_dir/${current_date} >> $backup_dir/history.log
fi

backup=$backup_dir/${current_date}/${filename}.${current_time}
if [ -f ${original} ];
then
    cp ${original} ${backup}
    echo "[${datetime}] [B] ${original} to ${backup}" >> $backup_dir/history.log
fi

vim $@

datetime=`date +"%Y-%m-%d.%H:%M:%S"`
current_date=`date +"%Y-%m-%d"`
current_time=`date +"%H:%M:%S"`
newfile=$backup_dir/${current_date}/${filename}.${current_time}

if [ -f ${original} ]; then
    if [ -f ${backup} ]; then
        original_sha=`sha1sum ${backup} |awk -F ' ' '{print $1}'`
        newfile_sha=`sha1sum ${original} |awk -F ' ' '{print $1}'`

        if [ $original_sha = $newfile_sha ];
        then
            echo "[${datetime}] --- " >> $backup_dir/history.log
            exit
        fi

    fi
    cp ${original} ${newfile}
    echo "[${datetime}] [M] ${original}" >> $backup_dir/history.log
    echo "[${datetime}] [B] ${original} to ${newfile}" >> $backup_dir/history.log

fi
echo "[${datetime}] --- " >> $backup_dir/history.log
exit
